package com.tuanzi.loan.web.bean.family;

import com.tuanzi.loan.business.entity.family.LoanChannelNdInfo;
import com.tuanzi.loan.business.service.family.LoanChannelNdInfoService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;

@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class LoanChannelNdInfoBean extends JSFInfoBean<LoanChannelNdInfo> {
    private static final long serialVersionUID = -4042919692993482039L;

    @Autowired
    private LoanChannelNdInfoService loanChannelNdInfoService;
    private String[] channels;

    @PostConstruct
    private void init() {
        String idStr = getParamFromRequest("id");
        long id = NumberUtils.toLong(idStr);
        if(StringUtils.isNoneBlank(idStr) && 0 != id){
            LoanChannelNdInfo one = loanChannelNdInfoService.findOne(id);
            if(null == one){
                forceRedirect("/views/family/WholeSaleManage/largeNewChannelList.xhtml");
                return;
            }
            this.$ = one;
            initChannels($);
        }else{
            changeStatusToAdd();
            this.$ = new LoanChannelNdInfo();
        }
    }

    private void initChannels(LoanChannelNdInfo loanChannelNdInfo){
        String channelInfo = loanChannelNdInfo.getChannelInfo();
        if(StringUtils.isNoneBlank(channelInfo)){
            this.channels = channelInfo.split(",");
        }
    }

    public void save(){
        if(StringUtils.isAnyBlank($.getChannel_nd(), $.getChannelNdName())){
            addErrorMessage("渠道或者渠道名不能为空");
            return;
        }

        if(channels != null && channels.length >0){
            this.$.setChannelInfo(String.join(",", channels));
        }
        loanChannelNdInfoService.saveOrUpdate($);
        addSuccessfullyMessage();
        changeStatusToView();
    }

    public String onReturn(){
        return redirect("/views/family/WholeSaleManage/largeNewChannelList.xhtml");
    }
}
